from rest_framework.views import exception_handler
from rest_framework_simplejwt.exceptions import AuthenticationFailed,TokenError,TokenBackendExpiredToken
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework import status
import logging
import traceback

class GlobalExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            response = self.get_response(request)
            print(type(response.data))
            # Handle None response
            if (isinstance(response.content,)):
                print('111111111111111')
                error_response = {
                    'status': 'success',
                    'code': 200,
                    'message': '成功返回数据',
                    'data': response.content,
                    'total': len(response.content)

                }
                response = Response(error_response, status=status.HTTP_204_NO_CONTENT)
                response.accepted_renderer = JSONRenderer()
                response.accepted_media_type = "application/json"
                response.renderer_context = {}
                response.render()

            if response is None:
                error_response = {
                    'status': 'error',
                    'code': 500,
                    'message': '服务器内部错误：响应为空'
                }
                response = Response(error_response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                response.accepted_renderer = JSONRenderer()
                response.accepted_media_type = "application/json"
                response.renderer_context = {}
                response.render()
                return response

            # Handle 401 Unauthorized
            if response.status_code == 401:
                error_response = {
                    'status': 'error',
                    'code': 401,
                    'message': '该用户未授权'
                }
                response = Response(error_response, status=status.HTTP_401_UNAUTHORIZED)
                response.accepted_renderer = JSONRenderer()
                response.accepted_media_type = "application/json"
                response.renderer_context = {}
                response.render()
                return response

            # Handle 204 No Content
            elif response.status_code == 204:
                error_response = {
                    'status': 'success',
                    'code': 204,
                    'message': '删除成功'
                }
                response = Response(error_response, status=status.HTTP_204_NO_CONTENT)
                response.accepted_renderer = JSONRenderer()
                response.accepted_media_type = "application/json"
                response.renderer_context = {}
                response.render()
            return response

        except ValueError as e:
            # Handle ValueError
            logging.error(f"ValueError occurred: {str(e)}")
            error_response = {
                'status': 'error',
                'code': 400,
                'message': str(e)
            }
            response = Response(error_response, status=status.HTTP_400_BAD_REQUEST)
            response.accepted_renderer = JSONRenderer()
            response.accepted_media_type = "application/json"
            response.renderer_context = {}
            response.render()
            return response

        except Exception as e:
            # Handle other exceptions
            stack_trace = traceback.format_exc()
            logging.error(f"Unexpected error occurred: {str(e)}\n{stack_trace}")
            error_response = {
                'status': 'error',
                'code': 500,
                'message': '服务器内部错误'
            }
            response = Response(error_response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            response.accepted_renderer = JSONRenderer()
            response.accepted_media_type = "application/json"
            response.renderer_context = {}
            response.render()
            return response

    @staticmethod
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
        
        if response is None:
            return Response({
                'status': 'error',
                'code': 500,
                'message': str(exc)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
        if isinstance(exc, (AuthenticationFailed, TokenError, TokenBackendExpiredToken)):
            response.status_code = status.HTTP_401_UNAUTHORIZED
            response.data = {
                'status': 'error',
                'code': 401,
                'message': str(exc)
            }
            
        return response
           
